import React, { useEffect, useState, useCallback } from 'react';
import { isEmpty, timeLeft } from '@/utils/common';
import { AsyncLoading, ModalWrap } from '@/design';
import { useSelector, useDispatch } from 'umi';
import styles from './reserveModal.less';

export default function (props: any) {
  const { reserveVisiable } = props;
  const dispatch = useDispatch()
  const { mealTimeDetail, mealTimeDetail: { location } } = useSelector((state: any) => state.store);
  const { bespeakStartTime } = useSelector((state: any) => state.order);
  const { currentstore } = useSelector((state: any) => state.currentstore);

  // 获取可预约时间列表
  useEffect(() => {
    if (reserveVisiable) {
      fetchMealTime();
    }
  }, [reserveVisiable])

  const fetchMealTime = () => {
    dispatch({
      type: 'store/fetchMealTime',
      payload: {
        braId: currentstore.braId
      }
    })
  }

  const handleSelectBespeakStartTime = (item: number) => {//保存选择的预约时间
    dispatch({
      type: 'order/saveBespeakStartTime',
      paylaod: item
    })
  }

  return (
    <ModalWrap headName={'預訂信息'} modalVisiable={reserveVisiable} onClickSure={props.onClickSure} btnName={'開始點餐'} onClose={props.onClose} hideFooter={isEmpty(mealTimeDetail.timeList)} disabled={!bespeakStartTime}>
      {isEmpty(mealTimeDetail) ? <AsyncLoading /> : 
      isEmpty(mealTimeDetail.timeList) ? <div className={styles.empty_timeList}>
        <p><span className={styles.close_icon} /></p>
        <p>{mealTimeDetail.message}</p>
      </div> : 
      <>
        <div className={styles.location_detail}>
          <span className={styles.location_icon}></span>
          <span className={`${styles.location_info} ${styles.location}`}>{location}</span>
        </div>
        <div className={styles.location_detail}>
          <span className={styles.location_info}>
            {`${bespeakStartTime ? `選擇預約時間為：${bespeakStartTime}` : '選擇時間:'}`}
          </span>
        </div>
        <ul className={styles.times_wrap}>
          {mealTimeDetail.timeList.map((item: any, index: number) => {
            return (<li className={`${bespeakStartTime === item ? styles.active : ''}`} key={`${item}_${index}`} onClick={() => { handleSelectBespeakStartTime(item) }}>
              <span>{item}</span>
              <span>{timeLeft(item)}</span>
            </li>)
          })}
        </ul>
      </>
      }
    </ModalWrap>
  )
}